#!/usr/bin/env bash

set -euo pipefail

name="$1"
command="$2"
binding="$3"

if [[ "$XDG_CURRENT_DESKTOP" == "KDE" ]]; then
  #kwriteconfig5 --file ~/.config/kglobalshortcutsrc --group "alacritty" --key "CustomShortcuts/$name" "$binding,none,$name"
  #kquitapp5 kglobalaccel && kstart5 kglobalaccel

#[alacritty.sh-3.desktop]
#_k_friendly_name=alacritty.sh
#_launch=F1,none,/home/morven/.local/bin/alacritty.sh
echo 'KDE need to setup hotkey manually'
else
  if gsettings list-recursively org.gnome.desktop.wm.keybindings | grep "'$binding'"; then
    echo "Hotkey has been used"
    if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
      exit 1
    else
      return 1
    fi
  fi

  custom_keybindings="$(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings)"
  custom_keybindings=${custom_keybindings:1:-1}

  modified_keybindings='['

  IFS=',' read -r -a keybindings <<<"$custom_keybindings"
  for i in "${!keybindings[@]}"; do
    keybinding=$(echo "${keybindings[$i]}" | xargs | sed "s/^'//;s/'$//")
    modified_keybindings="$modified_keybindings'${keybinding}', "

    if [[ "$keybinding" == "/$name/" ]]; then
      echo "$keybinding has been configured, overwritting keybinding..."
      gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/$name/ command "'$command'"
      gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/$name/ binding "'$binding'"
      if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
        exit 1
      else
        return 1
      fi
    fi

    if [[ "$(gsettings get org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:$keybinding command)" == "'$command'" ]]; then
      echo "Command '$command' has been bind to hotkey: $(gsettings get org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:$keybinding binding)"
      if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
        exit 0
      else
        return 0
      fi
    fi

    if [[ "$(gsettings get org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:$keybinding binding)" == "'$binding'" ]]; then
      echo "Hotkey has been used by $(gsettings get org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:$keybinding command)"
      if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
        exit 1
      else
        return 1
      fi
    fi
  done

  modified_keybindings="$modified_keybindings'/$name/']"

  echo "Setting custom-keybindings to $modified_keybindings"
  gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "$modified_keybindings"

  echo "Adding keybinding: /$name/..."
  gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/$name/ name "'$name'"
  gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/$name/ command "'$command'"
  gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:/$name/ binding "'$binding'"
fi
